class SQLFormatter {
    static format(sql, options = {}) {
        try {
            if (!sql || typeof sql !== 'string') {
                return { success: false, error: '请提供有效的SQL语句' };
            }

            const {
                indentSize = 4,
                keywordCase = 'upper', // 'upper', 'lower', 'preserve'
                commaStyle = 'trailing', // 'trailing', 'leading'
                linesBetweenQueries = 1
            } = options;

            // 清理输入
            sql = sql.trim();
            if (!sql) {
                return { success: false, error: 'SQL语句不能为空' };
            }

            // 分割多条语句
            const statements = this.splitStatements(sql);
            const formattedStatements = [];

            for (const statement of statements) {
                if (statement.trim()) {
                    const formatted = this.formatSingleStatement(statement.trim(), {
                        indentSize,
                        keywordCase,
                        commaStyle
                    });
                    formattedStatements.push(formatted);
                }
            }

            const result = formattedStatements.join('\n'.repeat(linesBetweenQueries + 1));
            
            return {
                success: true,
                data: result,
                stats: {
                    originalLength: sql.length,
                    formattedLength: result.length,
                    statementCount: formattedStatements.length,
                    indentSize,
                    keywordCase,
                    commaStyle
                }
            };
        } catch (error) {
            return { success: false, error: `格式化失败: ${error.message}` };
        }
    }

    static formatSingleStatement(sql, options) {
        const { indentSize, keywordCase, commaStyle } = options;
        
        // 基础清理
        sql = this.cleanSQL(sql);
        
        // 标记化
        const tokens = this.tokenize(sql);
        
        // 格式化
        return this.formatTokens(tokens, { indentSize, keywordCase, commaStyle });
    }

    static cleanSQL(sql) {
        // 移除多余的空格和换行
        return sql
            .replace(/\s+/g, ' ')
            .replace(/\s*([(),;])\s*/g, '$1')
            .replace(/\s*=\s*/g, ' = ')
            .replace(/\s*([<>!]=?)\s*/g, ' $1 ')
            .trim();
    }

    static splitStatements(sql) {
        const statements = [];
        let current = '';
        let inString = false;
        let stringChar = '';
        let i = 0;

        while (i < sql.length) {
            const char = sql[i];
            
            if (!inString && (char === '"' || char === "'" || char === '`')) {
                inString = true;
                stringChar = char;
                current += char;
            } else if (inString && char === stringChar) {
                // 检查是否为转义字符
                if (i > 0 && sql[i - 1] === '\\') {
                    current += char;
                } else {
                    inString = false;
                    stringChar = '';
                    current += char;
                }
            } else if (!inString && char === ';') {
                statements.push(current);
                current = '';
            } else {
                current += char;
            }
            i++;
        }

        if (current.trim()) {
            statements.push(current);
        }

        return statements;
    }

    static tokenize(sql) {
        const keywords = [
            'SELECT', 'FROM', 'WHERE', 'JOIN', 'INNER', 'LEFT', 'RIGHT', 'FULL', 'OUTER',
            'ON', 'AND', 'OR', 'NOT', 'IN', 'EXISTS', 'BETWEEN', 'LIKE', 'IS', 'NULL',
            'INSERT', 'INTO', 'VALUES', 'UPDATE', 'SET', 'DELETE', 'CREATE', 'TABLE',
            'ALTER', 'DROP', 'INDEX', 'ORDER', 'BY', 'GROUP', 'HAVING', 'DISTINCT',
            'AS', 'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'UNION', 'ALL', 'LIMIT',
            'OFFSET', 'FETCH', 'FIRST', 'ROWS', 'ONLY', 'WITH', 'CTE', 'RECURSIVE'
        ];

        const tokens = [];
        let current = '';
        let inString = false;
        let stringChar = '';
        
        for (let i = 0; i < sql.length; i++) {
            const char = sql[i];
            
            if (!inString && (char === '"' || char === "'" || char === '`')) {
                if (current) {
                    tokens.push({ type: 'identifier', value: current });
                    current = '';
                }
                inString = true;
                stringChar = char;
                current = char;
            } else if (inString && char === stringChar) {
                current += char;
                tokens.push({ type: 'string', value: current });
                current = '';
                inString = false;
                stringChar = '';
            } else if (inString) {
                current += char;
            } else if (/\s/.test(char)) {
                if (current) {
                    const upperCurrent = current.toUpperCase();
                    if (keywords.includes(upperCurrent)) {
                        tokens.push({ type: 'keyword', value: current });
                    } else {
                        tokens.push({ type: 'identifier', value: current });
                    }
                    current = '';
                }
            } else if ('(),;'.includes(char)) {
                if (current) {
                    const upperCurrent = current.toUpperCase();
                    if (keywords.includes(upperCurrent)) {
                        tokens.push({ type: 'keyword', value: current });
                    } else {
                        tokens.push({ type: 'identifier', value: current });
                    }
                    current = '';
                }
                tokens.push({ type: 'punctuation', value: char });
            } else {
                current += char;
            }
        }
        
        if (current) {
            const upperCurrent = current.toUpperCase();
            if (keywords.includes(upperCurrent)) {
                tokens.push({ type: 'keyword', value: current });
            } else {
                tokens.push({ type: 'identifier', value: current });
            }
        }
        
        return tokens;
    }

    static formatTokens(tokens, options) {
        const { indentSize, keywordCase, commaStyle } = options;
        const indent = ' '.repeat(indentSize);
        let result = '';
        let currentIndent = 0;
        let newLineNeeded = false;
        
        for (let i = 0; i < tokens.length; i++) {
            const token = tokens[i];
            const nextToken = tokens[i + 1];
            const prevToken = tokens[i - 1];
            
            if (token.type === 'keyword') {
                const keyword = token.value.toUpperCase();
                let formattedKeyword = token.value;
                
                // 应用关键字大小写
                if (keywordCase === 'upper') {
                    formattedKeyword = keyword;
                } else if (keywordCase === 'lower') {
                    formattedKeyword = keyword.toLowerCase();
                }
                
                // 处理换行和缩进
                if (this.shouldStartNewLine(keyword)) {
                    if (result) result += '\n';
                    result += indent.repeat(currentIndent) + formattedKeyword;
                    newLineNeeded = false;
                } else if (this.shouldIndentInward(keyword)) {
                    if (newLineNeeded && result) result += '\n';
                    currentIndent++;
                    result += indent.repeat(currentIndent) + formattedKeyword;
                    newLineNeeded = false;
                } else if (this.shouldIndentOutward(keyword)) {
                    currentIndent = Math.max(0, currentIndent - 1);
                    if (result) result += '\n';
                    result += indent.repeat(currentIndent) + formattedKeyword;
                    newLineNeeded = false;
                } else {
                    if (result && !result.endsWith(' ')) {
                        result += ' ';
                    }
                    result += formattedKeyword;
                }
            } else if (token.type === 'punctuation') {
                if (token.value === ',') {
                    if (commaStyle === 'trailing') {
                        result += token.value;
                        if (nextToken) {
                            result += '\n' + indent.repeat(currentIndent + 1);
                        }
                    } else { // leading
                        if (result) result += '\n' + indent.repeat(currentIndent + 1);
                        result += token.value + ' ';
                    }
                } else {
                    result += token.value;
                    if (token.value === '(' && nextToken) {
                        newLineNeeded = true;
                    }
                }
            } else {
                if (result && !result.endsWith(' ') && !result.endsWith('\n') && !result.endsWith('(')) {
                    result += ' ';
                }
                result += token.value;
            }
        }
        
        return result;
    }

    static shouldStartNewLine(keyword) {
        return ['SELECT', 'FROM', 'WHERE', 'GROUP', 'ORDER', 'HAVING', 'UNION'].includes(keyword);
    }

    static shouldIndentInward(keyword) {
        return ['JOIN', 'INNER', 'LEFT', 'RIGHT', 'FULL'].includes(keyword);
    }

    static shouldIndentOutward(keyword) {
        return false; // 根据需要调整
    }

    static minify(sql) {
        try {
            if (!sql || typeof sql !== 'string') {
                return { success: false, error: '请提供有效的SQL语句' };
            }

            // 移除注释
            let minified = sql
                .replace(/--[^\r\n]*/g, '') // 单行注释
                .replace(/\/\*[\s\S]*?\*\//g, '') // 多行注释
                .replace(/\s+/g, ' ') // 多个空格变为单个
                .replace(/\s*([(),;=<>!])\s*/g, '$1') // 操作符周围的空格
                .trim();

            return {
                success: true,
                data: minified,
                stats: {
                    originalLength: sql.length,
                    minifiedLength: minified.length,
                    compressionRatio: ((sql.length - minified.length) / sql.length * 100).toFixed(2)
                }
            };
        } catch (error) {
            return { success: false, error: `压缩失败: ${error.message}` };
        }
    }

    static validate(sql) {
        try {
            if (!sql || typeof sql !== 'string') {
                return { success: false, error: '请提供有效的SQL语句' };
            }

            const issues = [];
            const suggestions = [];

            // 基础语法检查
            const tokens = this.tokenize(sql);
            let openParens = 0;
            let hasSelect = false;
            let hasFrom = false;

            for (const token of tokens) {
                if (token.type === 'punctuation') {
                    if (token.value === '(') openParens++;
                    else if (token.value === ')') openParens--;
                } else if (token.type === 'keyword') {
                    const keyword = token.value.toUpperCase();
                    if (keyword === 'SELECT') hasSelect = true;
                    if (keyword === 'FROM') hasFrom = true;
                }
            }

            // 检查括号匹配
            if (openParens !== 0) {
                issues.push('括号不匹配');
            }

            // 检查基础语法
            if (hasSelect && !hasFrom && !sql.toUpperCase().includes('VALUES')) {
                suggestions.push('SELECT语句通常需要FROM子句');
            }

            // 检查常见问题
            if (sql.includes('SELECT *')) {
                suggestions.push('避免使用SELECT *，明确指定需要的列');
            }

            if (sql.toUpperCase().includes(' = NULL')) {
                issues.push('使用IS NULL而不是= NULL');
            }

            return {
                success: true,
                data: {
                    isValid: issues.length === 0,
                    issues,
                    suggestions,
                    tokenCount: tokens.length
                }
            };
        } catch (error) {
            return { success: false, error: `验证失败: ${error.message}` };
        }
    }

    static getTableNames(sql) {
        try {
            const tokens = this.tokenize(sql);
            const tables = new Set();
            
            for (let i = 0; i < tokens.length - 1; i++) {
                const token = tokens[i];
                const nextToken = tokens[i + 1];
                
                if (token.type === 'keyword' && 
                    ['FROM', 'JOIN', 'INTO', 'UPDATE'].includes(token.value.toUpperCase()) &&
                    nextToken && nextToken.type === 'identifier') {
                    tables.add(nextToken.value);
                }
            }
            
            return { success: true, data: Array.from(tables) };
        } catch (error) {
            return { success: false, error: `提取表名失败: ${error.message}` };
        }
    }
}